package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private IStrategyService strategyService;

    @GetMapping
    public List<Region> list(Integer state) {
        List<Region> list = regionService.list(state);
        return list;
    }

    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo listStrategiesJson(StrategyQuery qo){
        qo.setPageSize(8);
        return strategyService.query(qo);
    }
    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void listStrategies(StrategyQuery qo, HttpServletResponse response) throws Exception {
        //首先是不分页
        qo.setPageSize(0);
        //查询状态为推荐的
        qo.setState(Strategy.STATE_HOT);
        PageInfo<?> comments = strategyService.query(qo);
        qo.setPageSize(8);
        qo.setState(null);
        PageInfo<?> alls = strategyService.query(qo);
        Configuration config=new Configuration(Configuration.VERSION_2_3_23);
        //设置模板的位置
        config.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));

        //获取模板中的文件内容
        Template template = config.getTemplate("strategyTemplate.ftl", "utf-8");
        //数据的合成
        HashMap<Object,Object> hash=new HashMap<>();
        hash.put("comments",comments);
        hash.put("alls",alls);
        template.process(hash,response.getWriter());

    }
}
